package com.controller;

import com.alipay.api.AlipayApiException;
import com.annotation.IgnoreAuth;
import com.entity.AlipayEntity;
import com.entity.YonghuEntity;
import com.model.AlipayBean;
import com.service.PayService;
import com.service.YonghuService;
import com.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.UUID;

@RestController
@CrossOrigin(origins = "*") // 允许所有跨域请求
public class PayController {
    @Autowired
    private PayService aliPayService;

    @Autowired
    private YonghuService userService;

    @RequestMapping(value = "/alipay/pay")
    public R alipay(@RequestParam Map<String, Object> params) throws AlipayApiException {
        AlipayBean order = new AlipayBean();
        String out_trade_no = UUID.randomUUID().toString();
        order.setOut_trade_no(out_trade_no);
        order.setTotal_amount(params.get("totalAmount").toString());
        System.out.println(order);
        AlipayEntity entity = new AlipayEntity();
        entity.setId(out_trade_no);
        entity.setUser(Long.parseLong(params.get("userId").toString()));
        entity.setAmount(Double.parseDouble(params.get("totalAmount").toString()));
        aliPayService.insert(entity);
        return R.ok().put("data", aliPayService.aliPay(order));
    }

    @IgnoreAuth
    @RequestMapping("/alipay/notifyUrl")
    public void notifyUrl(HttpServletRequest request, HttpServletResponse response) {
        String out_trade_no=null;
        Map<String, String[]> parameterMap = request.getParameterMap();
        for (String s : parameterMap.keySet()) {
            String[] strings = parameterMap.get(s);
            for (int i = 0; i < strings.length; i++) {
                if (s.equals("out_trade_no")){
                    out_trade_no=strings[i];
                }
            }
        }
        AlipayEntity entity = aliPayService.selectById(out_trade_no);
        YonghuEntity user = userService.selectById(entity.getUser());
        user.setMoney((float) (user.getMoney() + entity.getAmount()));
        userService.updateById(user);
        entity.setPayed(true);
        aliPayService.updateById(entity);
    }
}
